import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flauto.dart';
import 'package:flutter_sound/flutter_sound_player.dart';
import 'package:flutter_sound/flutter_sound_recorder.dart';
import 'package:path_provider/path_provider.dart';

main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() {
    // TODO: implement createState
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  bool isHide = true;
  int costTime = 0;
  FlutterSoundPlayer playerModule;
  FlutterSoundRecorder recorderModule;
  t_CODEC _codec = t_CODEC.CODEC_AAC;
  List<String> records = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init();
  }

  init() async {
    playerModule = await FlutterSoundPlayer().initialize();
    recorderModule = await FlutterSoundRecorder().initialize();
  }

  Future<bool> fileExists(String path) async {
    return await File(path).exists();
  }

  // In this simple example, we just load a file in memory.This is stupid but just for demonstration  of startPlayerFromBuffer()
  Future<Uint8List> makeBuffer(String path) async {
    try {
      if (!await fileExists(path)) return null;
      File file = File(path);
      file.openRead();
      var contents = await file.readAsBytes();
      print('The file is ${contents.length} bytes long.');
      return contents;
    } catch (e) {
      print(e);
      return null;
    }
  }

  //播放录音
  Future<void> startPlayer(String url) async {
    if(url==null){
      log("空的");
      return;
    }else{
      await playerModule.startPlayer(
          url,codec: _codec,whenFinished: (){
          log("播放完成");
        }
      );
    }

  }
  //开始录音
  startRecord()async{
    setState(() {
      isHide = false;
    });
    log("开始录音");
    Directory tempDir = await getTemporaryDirectory();
    String path = await recorderModule.startRecorder(
      uri:
      '${tempDir.path}/${DateTime.now().millisecondsSinceEpoch}-${Platform.isAndroid?"mp3":"m4a"}',
      codec: _codec,
    );
    records.add(path);
    recorderModule.onRecorderStateChanged.listen((e) {
      if (e != null && e.currentPosition != null) {
        DateTime date = new DateTime.fromMillisecondsSinceEpoch(
            e.currentPosition.toInt(),
            isUtc: true);
        setState(() {
          costTime = date.second;
        });
      }
    });
  }
  //停止录音
  stopRecord()async{
    await recorderModule.stopRecorder();
    setState(() {
      isHide = true;
      costTime = 0;
    });
  }
  //取消录音
  cancelRecord()async{
    records.removeLast();
    await recorderModule.stopRecorder();
    setState(() {
      isHide = true;
      costTime = 0;
    });
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("录音demo"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Opacity(
              opacity: isHide ? 0.0 : 1.0,
              child: Container(
                width: 120,
                height: 50,
                decoration: BoxDecoration(
                    color: Colors.grey.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(10)),
                alignment: Alignment.center,
                child: Text(costTime.toString()),
              ),
            ),
            SizedBox(
              height: 20,
            ),
            GestureDetector(
              onTapDown: (x) =>startRecord(),
              onTapUp: (x) =>stopRecord(),
              onTapCancel: ()=>cancelRecord(),
              child: FloatingActionButton(child: Icon(Icons.volume_up),),
            ),
            SizedBox(height: 20,),
            FloatingActionButton(
              child: Icon(Icons.play_arrow),
              onPressed: ()=>startPlayer(records[records.length-1]),
            ),
            Expanded(
              child: ListView.builder(itemBuilder: (context,index){
                return RaisedButton(
                    child: Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(16),
                        child: Text(records[index].toString())),
                    onPressed: (){
                      startPlayer(records[index]);
                    },
                );
              },
              itemCount: records.length,),
            )
          ],
        ),
      ),
    );
  }
}


